package com.javabasic.algorithm.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see     [219. 存在重复元素 II - 力扣（LeetCode）](https://leetcode.cn/problems/contains-duplicate-ii/description/)
 * @since Created by work on 2023/12/20 21:43
 */
public class ContainsDuplicateII {

    /**
     * TTL
     * @param nums
     * @param k
     * @return
     */
    public boolean containsNearbyDuplicate2(int[] nums, int k) {
        int len = nums.length;
        List<Integer> segmentNums = new ArrayList<>();
        if (len <= k + 1) {
            for (int num : nums) {
                if (segmentNums.contains(num)) {
                    return Boolean.TRUE;
                }
                segmentNums.add(num);
            }
            return Boolean.FALSE;
        }

        for (int i = 0; i <= k; i++) {
            if (segmentNums.contains(nums[i])) {
                return Boolean.TRUE;
            }
            segmentNums.add(nums[i]);
        }

        for (int i = k + 1; i < len; i++) {
            segmentNums.remove(0);
            if (segmentNums.contains(nums[i])) {
                return Boolean.TRUE;
            }
            segmentNums.add(nums[i]);
        }
        return Boolean.FALSE;
    }

    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> numToIndexMap = new HashMap<>();

        int len = nums.length;
        Integer index;
        for (int i = 0; i < len; i++) {
            index = numToIndexMap.getOrDefault(nums[i], i);
            if (Objects.equals(index, i)) {
                numToIndexMap.put(nums[i], i);
                continue;
            }
            if (i - index <= k) {
                return Boolean.TRUE;
            }
            numToIndexMap.put(nums[i], i);
        }
        return Boolean.FALSE;
    }

}
